﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;

namespace YouTubeDownloadExtension
{
    public sealed class Downloader
    {
        private readonly Uri uri;
        private string fileName;
        private string downloadFolder;

        public Downloader(Uri uri, string fileName)
        {
            this.uri = uri;
            FileName = fileName;
        }

        public string FileName
        {
            get { return fileName; }
            set
            {
                if (value == null)
                    throw new ArgumentNullException("value");
                if (value == string.Empty)
                    throw new ArgumentException("Empty file name.", "value");
                fileName = RemoveInvalidCharacters(value, Path.GetInvalidFileNameChars());
            }
        }

        public string DownloadFolder
        {
            get { return string.IsNullOrEmpty(downloadFolder) ? Directory.GetCurrentDirectory() : downloadFolder; }
            set { downloadFolder = RemoveInvalidCharacters(value, Path.GetInvalidPathChars()); }
        }

        public void DownloadFile()
        {
            var downloadPath = CreateDownloadPath();

            using (var client = new WebClient())
            {
                client.DownloadFile(uri, downloadPath);
            }  
        }

        private string CreateDownloadPath()
        {
            Directory.CreateDirectory(DownloadFolder);
            return Path.Combine(downloadFolder, FileName);
        }

        private static string RemoveInvalidCharacters(string text, IEnumerable<char> invalidCharacters)
        {
            var validatedCharacters = text.Where(character => invalidCharacters.Contains(character) == false);
            return new string(validatedCharacters.ToArray());
        }        
    }
}
